# IO操作
import os


def read_file(file_path):
    with open(file_path, mode='r', encoding='UTF-8') as f:        # 读文本文件
    # with open(file_path, mode='w', encoding='UTF-8') as f:      # 写文件，用'w'模式会将源文件覆盖
    # with open(file_path, mode='a', encoding='UTF-8') as f:      # 写文件，在源文件后添加内容，不覆盖
    # with open(file_path, mode='rb') as f:                       # 以二进制方式打开文件
    #     content = f.read()
        content = f.readline()
        print(content)


# np = os.path.join(os.path.abspath('.'), 'README1.md')
# read_file(np)


print('//' * 100)
# StringIO, BytesIO
from io import BytesIO, StringIO
def io_utils():
    strIO = StringIO()
    strIO.write('hello, stil')
    print(strIO.getvalue())
    lines = StringIO('abcdefghijklmn\r\nopqrstuvwxyz').readlines()
    for line in lines:
        print(line)
def byte_utils():
    br = BytesIO('hello, stil'.encode(encoding='UTF-8')).read()
    print(br.decode(encoding='UTF-8'))

    bio = BytesIO()
    bio.write('abcdefghijklmnopqrstuvwxyz'.encode(encoding='UTF-8'))
    bv = bio.getvalue()
    print(bv)
    print(bv.decode(encoding='UTF-8'))

print('//' * 100)



# 序列化
import pickle
class Person():
    def __init__(self, name, age):
        self.name = name
        self.age = age
    def __str__(self):
        return 'name={0}, age={1}'.format(self.name, self.age)

pbytes = pickle.dumps(Person('magoo', 23))
print(pbytes)
pl = pickle.loads(pbytes, encoding='UTF-8', errors='ignore')
print(pl)

np = os.path.join(os.path.abspath('.'), 'README1.md')
with open(np, 'wb') as f:
    pickle.dump(Person('magoo', 23), f)

with open(np, 'rb') as f:
    person = pickle.load(f)
    print(person, 'load>>>>>>>>>>>>>>>>>>>>>>>>>>>>')


import json
pstr = json.dumps(Person('magoo', 23), default=lambda obj: obj.__dict__)
print(pstr)
def dict2json(d):
    return Person(d['name'],d['age'])
person = json.loads(pstr, object_hook=dict2json)
print('>>>', person, 'type={0}'.format(type(person)))

print('//' * 100)

# 文件以及文件目录操作
import os
import shutil

cpath = os.path.abspath('.')
print('当前路径：{0}'.format(cpath))
npath = os.path.join(cpath, 'newdir')
print('新路径：{0}'.format(npath))
os.mkdir(npath)     # 创建目录，如果以存在会报错
os.rmdir(npath)     # 删除目录

filepath = os.path.abspath('.')
filepath = os.path.join(filepath, 'README1.md')
ps = os.path.split(filepath)   # 获取叶子节点目录名称
print('ps type = {0}, ps={1}'.format(type(ps), ps))
np = os.path.join(os.path.abspath('.'))
nps = os.path.splitext(np)  # 获取文件名后缀，如果为目录，则没有后缀
print('nps = {0}'.format(nps))



